from langchain_neo4j import Neo4jGraph
from dotenv import load_dotenv
import os

class CompanyNodeService:
    def __init__(self):
        load_dotenv()
        #连接Neo4j数据库
        self.graph = Neo4jGraph(
            url=os.getenv("NEO4J_URI"),
            username=os.getenv("NEO4J_USERNAME"),
            password=os.getenv("NEO4J_PASSWORD"),
        )
    #创建节点
    def create_company_node(self,**kwargs):
        try:
            cypher_str = "CREATE (c:Company {reg_date:$reg_date,risk_level:$risk_level, reg_no:$reg_no, name:$name, industry:$industry, legal_rep:$legal_rep, registered_capital:$registered_capital,status:$status})"
            self.graph.query(cypher_str,params=kwargs)
            return "创建成功"
        except Exception as e:
            print(e)
            return "创建失败"
    #查询节点
    def query_company_node(self,**kwargs):
        try:
            cypher_str = "MATCH (c:Company) RETURN c "
            data=self.graph.query(cypher_str)
            data_list=[]
            for i in range(0,len(data)):
                data_list.append(data[i]['c'])
            return data_list
        except Exception as e:
            print(e)
            return "查询失败！！！"
    #删除节点
    def delete_company_node(self,**kwargs):
        try:
            cypher_str = "MATCH (c:Company {reg_no:$reg_no}) DELETE c"
            self.graph.query(cypher_str,params=kwargs)
            return "删除节点成功"
        except Exception as e:
            print(e)
            return "删除节点失败"

    #如果公司节点不存在，则创建；如果已存在，则更新（或只更新某些字段）
    def update_company_node(self,**kwargs):
        try:
            cypher_str = """
               MERGE (c:Company {reg_no: $reg_no})
               ON CREATE SET 
                   c.reg_date = $reg_date,
                   c.risk_level = $risk_level,
                   c.name = $name,
                   c.industry = $industry,
                   c.legal_rep = $legal_rep,
                   c.registered_capital = $registered_capital,
                   c.status = $status
               ON MATCH SET 
                   c.reg_date = $reg_date,
                   c.risk_level = $risk_level,
                   c.name = $name,
                   c.industry = $industry,
                   c.legal_rep = $legal_rep,
                   c.registered_capital = $registered_capital,
                   c.status = $status
               """
            self.graph.query(cypher_str, params=kwargs)
            return "更新节点成功"
        except Exception as e:
            print(e)
            return "更新节点失败"

# if __name__ == '__main__':
#     a = CompanyNodeService()
#     data=a.query_company_node()
#     print(data)


